package org.example.util6;

import java.util.*;

public class LengthComparator implements Comparator<String> {
    @Override
//    public int compare(String o1, String o2) {
//        return o1.length() - o2.length();
//    }

    public int compare(String o1, String o2) {
        if (o1 == null && o2 == null) {
            return 0;
        }
        if (o1 == null) {
            return -1;
        }
        if (o2 == null) {
            return 1;
        }

        // 首先比较字符串的长度
        int lengthDifference = Integer.compare(o1.length(), o2.length());
        if (lengthDifference != 0) {
            return lengthDifference;
        }

        // 如果长度相同，再比较字典顺序
        return o1.compareTo(o2);
    }

    public static void main(String[] args) {
        //集合
        List<String> list = new ArrayList<String>();
        list.add("apple");
        list.add("bbbb");
        list.add("cc");
        list.add("bb");
        Collections.sort(list,new LengthComparator());
        System.out.printf(list.toString());
        //数组
        String[] friends={"cc","baby","aa"};
        Arrays.sort(friends,new LengthComparator());
        System.out.println(Arrays.toString(friends));
        //考虑字符串的长度和字典顺序进行排序
        List<String> strings = new ArrayList<>();
        strings.add("cc");
        strings.add("bb");
        strings.add("cherry");
        strings.add("date");
        Collections.sort(strings, new LengthComparator());
        // 输出排序后的列表
        System.out.println(strings);
    }
}
